<template>
  <ul class="al-list">
    <li
      class="al-item"
      v-for="(item, key) in letters"
      :key="key"
      :ref="item"
      @touchstart.prevent="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="handleLetterClick"
    >{{item}}</li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  computed: {
    letters: function () {
      // 将字母全部存到letters
      const letters = []
      for (let key in this.cities) {
        letters.push(key)
      }
      return letters
    }
  },
  data: function () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  // 修改页面，alphabet重新渲染，dom挂载在完成之后执行
  updated: function () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    // 点击事件触发之后，会接受一个事件对象
    handleLetterClick: function (e) {
      // 向外触发一个change事件，并把事件对象里面的属性传给要监听change事件的函数
      this.bus.$emit('change', e.target.innerText)
    },
    handleTouchStart: function () {
      this.touchStatus = true
    },
    handleTouchMove: function (e) {
      if (this.touchStatus) {
        // 滚动加载函数节流
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          // 首字母距离顶部的距离
          // 这个值是的固定的值，但是我们每次滑动都会创建这个变量
          // const startY = this.$refs['A'][0].offsetTop
          // 当前字母距离顶部的位置
          const touchY = e.touches[0].clientY - 81
          // 当前字母是第几个数字
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.bus.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd: function () {
      this.touchStatus = false
    }

  }
}
</script>

<style lang="stylus" scope>
@import '~@/assets/styles/varibles.styl';

.al-list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  top: 1.58rem;
  right: 0;
  bottom: 0;
  width: 0.3rem;
  padding-right: 0.05rem;

  .al-item {
    line-height: 0.4rem;
    text-align: center;
    color: $bgColor;
  }
}
</style>
